"use strict";
const jwt = require("jsonwebtoken");
const Controller = require("egg").Controller;

class BaseController extends Controller {

  // 验证请求参数
  verifytParams(dto) {
    try {
      //先进行解析
      const { requiredKeys, paramKeys } = this.ctx.helper.getRequiredKey(dto);
      // 校验必传参数
      let requestParams = {};

      //根据请求方式返回不同的参数给requestParams(工具函数)
      if (this.ctx.request.method === 'POST' || this.ctx.request.method === 'PUT') {
        requestParams = this.ctx.request.body;
      } else {
        requestParams = this.ctx.query;
      }
      //检查出必须传递的值,如果没有必须要求传递的值,则返回XX值必传
      const checkRequiredRes = this.ctx.helper.checkRequired(
        requestParams,
        requiredKeys
      );
      if (checkRequiredRes) throw checkRequiredRes;
      
      // 生成请求参数,将requestParams中所有包含paramsKeys中的key值找到对应的值,然后返回结果.
      const params = this.ctx.helper.createParams(requestParams, paramKeys);
    
      //成功返回和错误返回
      return this.ctx.helper.deepCopy({
        success: true,
        params: params,
        msg: ''
      })
    } catch (err) {
      return {
        success: false,
        params: {},
        msg: err
      }
    }

  }

  //对请求进行统一返回封装
  async request(){
    
  }

  //封装成功请求
  async success(data, msg = "操作成功") {
    this.ctx.status = 200;
    this.ctx.body = {
      code: 0,
      data,
      msg,
    };
  }

  //封装错误请求
  async error(msg, data = null, status = 200) {
    // console.log('逻辑错误', msg)
    // this.ctx.logger.error(new Error(msg));
    this.ctx.status = status;
    this.ctx.body = {
      code: 1,
      data,
      msg: msg || "系统错误",
    };
  }

  //封装列表请求
  async listSuccess(records, total, msg = "操作成功") {
    this.ctx.body = {
      data: {
        records,
        total,
      },
      code: 0,
      msg,
    };
  }

  // 返回请求头
  getRequestHeader(ctx) {
    return ctx.request.header;
  }

  // 获取当前登录用户
  getLoginUser () {
    return new Promise((resolve, reject) => {
      const token = this.ctx.request.header.authorization.replace("Bearer ", "")
      jwt.verify(token, this.config.jwt.secret, async (err, res) => {
        // return res;
        if (err) {
          reject('token解析失败')
        } else {
          resolve(res);
        }
      })
    })
  }
}

module.exports = BaseController;
